package com.springcloud.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * 局部过滤器实现后不能马上生效，需要进行配置：
 */
public class AuthFilter implements GatewayFilter, Ordered {
    // 初始化黑名单
    private static List<String> blackList = new ArrayList<>();

    static {
        blackList.add("zhangsan");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取request中的参数
        MultiValueMap<String, String> params = request.getQueryParams();

        for (List<String> values : params.values()) {
            for (String v : values) {
                if (blackList.contains(v)) {
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    String data = "该账号不允许访问";
                    DataBuffer dataBuffer = response.bufferFactory().wrap(data.getBytes());
                    response.getHeaders().add("Content-Type", "application/json;charset=utf-8");

                    return response.writeWith(Mono.just(dataBuffer));
                }
            }
        }


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
